<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编码" prop="orderNumber" style="margin-right: 50px;margin-bottom: 30px;">
        <el-input
          v-model="queryParams.orderNumber"
          placeholder="请输入订单编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="卖家姓名" prop="sellerName" style="margin-right: 50px;margin-bottom: 30px;">
        <el-input
          v-model="queryParams.sellerName"
          placeholder="请输入卖家姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="货物名称" prop="goodsName" style="margin-right: 50px;margin-bottom: 30px;">
        <el-input
          v-model="queryParams.goodsName"
          placeholder="请输入货物名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="仓库类型" prop="cktype" style="margin-right: 50px;margin-bottom: 30px;">
        <el-input
          v-model="queryParams.cktype"
          placeholder="请输入仓库类型"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="定金状态" prop="depositPaid" style="margin-right: 30px;margin-bottom: 30px;">
        <el-select v-model="queryParams.depositPaid" placeholder="订单状态" clearable>
          <el-option
            v-for="dict in dict.type.lg_order_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="余款金额" style="margin-right: 30px;margin-bottom: 30px;">
        <el-row>
          <el-col :span="11">
            <el-input
              v-model="priceRange[0]"
              placeholder="最小价格"
              style="width: 100%;"
              type="number"
            ></el-input>
          </el-col>
          <el-col :span="2" class="text-center" style="line-height: 32px;margin-bottom: 30px;">
            -
          </el-col>
          <el-col :span="11">
            <el-input
              v-model="priceRange[1]"
              placeholder="最大价格"
              style="width: 100%;"
              type="number"
            ></el-input>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="创建时间" style="margin-right: 30px;margin-bottom: 30px;margin-bottom: 30px;">
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['order:every:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['order:every:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['order:every:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['order:every:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="everyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" type="index" width="60">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
<!--      <el-table-column label="id" align="center" prop="id" />-->
      <el-table-column label="订单编号" align="center" prop="orderNumber" />
      <el-table-column label="卖家姓名" align="center" prop="sellerName" />
      <el-table-column label="卖家联系方式" align="center" prop="sellerContact" />
      <el-table-column label="货物名称" align="center" prop="goodsName" />
      <el-table-column label="卖家提供重量" align="center">
        <template slot-scope="scope">
          {{ scope.row.providedWeight }} kg
        </template>
      </el-table-column>
      <el-table-column label="货物数量" align="center" prop="goodsQuantity" />
      <el-table-column label="货物单位" align="center" prop="goodsUnit" />
<!--      <el-table-column label="预计存储天数" align="center" prop="storageDays" />-->
<!--      <el-table-column label="起始地" align="center" prop="origin" />-->
<!--      <el-table-column label="目的地" align="center" prop="destination" />-->
<!--      <el-table-column label="仓库地址" align="center" prop="warehouseAddress" />-->
<!--      <el-table-column label="距离" align="center" prop="distance" />-->
      <el-table-column label="仓库类型" align="center" prop="cktype" />
<!--      <el-table-column label="预估货物费用" align="center" prop="freightCost" />-->
<!--      <el-table-column label="预估价格" align="center" prop="estimatedPrice" />-->
<!--      <el-table-column label="最终价格" align="center" prop="finalGoodsPrice" />-->
<!--      <el-table-column label="最终运费" align="center" prop="finalFreightPrice" />-->
<!--      <el-table-column label="需要支付定金" align="center" prop="depositRequired" />-->
      <el-table-column label="尾款支付金额" align="center" prop="paymentAmount" />
      <el-table-column label="是否支付定金" align="center" prop="depositPaid">
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.lg_order_status" :value="scope.row.depositPaid"/>
                </template>
      </el-table-column>
<!--      <el-table-column label="创建人" align="center" prop="createBy" />-->
      <el-table-column label="创建时间" width="150" align="center" prop="createTime" />
<!--      <el-table-column label="修改人" align="center" prop="updateBy" />-->
<!--      <el-table-column label="修改时间" align="center" prop="updateTime" />-->


      <el-table-column label="操作" align="center"  width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handlexq(scope.row)"
            v-hasPermi="['order:every:edit']"
          >查看详情</el-button>

          <el-button
            type="warning"
            plain
            icon="el-icon-thumb"
            size="mini"
            @click="handleDriver(scope.row)"
            v-hasPermi="['order:every:driver']"
            v-if="scope.row.depositPaid == 3 || scope.row.depositPaid == 4 || scope.row.depositPaid == 8"
          >
            {{ assignedOrders.includes(scope.row.logisticsOrderNumber || scope.row.orderNumber) ? '更改司机' : '指派司机' }}
          </el-button>
            <el-button
              type="warning"
              plain
              icon="el-icon-thumb"
              size="mini"
              @click="handleCar(scope.row)"
              v-hasPermi="['order:every:car']"
              v-if="scope.row.depositPaid == 4 || scope.row.depositPaid == 8"
            >
              {{ assignedOrder.includes(scope.row.logisticsOrderNumber || scope.row.orderNumber) ? '更改车辆' : '指派车辆' }}
            </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
<!--    //查看详情-->
    <el-dialog title="详情页面" :visible.sync="showDetailDialog" width="50%">
      <el-descriptions border column="2">
        <el-descriptions-item label="订单编号">{{ detail.orderNumber }}</el-descriptions-item>
        <el-descriptions-item label="卖家姓名">{{ detail.sellerName }}</el-descriptions-item>
        <el-descriptions-item label="卖家联系方式">{{ detail.sellerContact }}</el-descriptions-item>
        <el-descriptions-item label="货物名称">{{ detail.subGoodsName }}</el-descriptions-item>
        <el-descriptions-item label="卖家提供重量">{{ detail.providedWeight }}</el-descriptions-item>
        <el-descriptions-item label="货物数量">{{ detail.goodsQuantity }}</el-descriptions-item>

        <el-descriptions-item label="货物单位">{{ detail.goodsUnit }}</el-descriptions-item>
<!--        <el-descriptions-item label="货物单位"> {{ getGoodsUnitName(detail.goodsUnit) }}</el-descriptions-item>-->
        <el-descriptions-item label="预计存储天数">{{ detail.storageDays }}</el-descriptions-item>
        <el-descriptions-item label="起始地">{{ detail.origin }}</el-descriptions-item>
        <el-descriptions-item label="目的地">{{ detail.destination }}</el-descriptions-item>
        <el-descriptions-item label="仓库地址">{{ detail.warehouseAddress }}</el-descriptions-item>
        <el-descriptions-item label="距离">{{ detail.distance }}</el-descriptions-item>
        <el-descriptions-item label="仓库类型">{{ detail.cktype }}</el-descriptions-item>
        <el-descriptions-item label="预估货运费用">{{ detail.freightCost }}</el-descriptions-item>
        <el-descriptions-item label="预估存储价格">{{ detail.estimatedPrice }}</el-descriptions-item>
        <el-descriptions-item label="最终运费价格">{{ detail.finalFreightPrice }}</el-descriptions-item>
        <el-descriptions-item label="最终存储价格">{{ detail.finalGoodsPrice }}</el-descriptions-item>
        <el-descriptions-item label="需要支付定金">{{ detail.depositRequired }}</el-descriptions-item>
        <el-descriptions-item label="尾款支付金额">{{ detail.paymentAmount }}</el-descriptions-item>
        <el-descriptions-item label="是否支付定金">
          <dict-tag :options="dict.type.lg_order_status" :value="detail.depositPaid"/>
        </el-descriptions-item>
<!--        <el-descriptions-item label="创建人">{{ detail.createBy }}</el-descriptions-item>-->
        <el-descriptions-item label="创建时间">{{ detail.createTime }}</el-descriptions-item>
<!--        <el-descriptions-item label="修改人">{{ detail.updateBy }}</el-descriptions-item>-->
        <el-descriptions-item label="修改时间">{{ detail.updateTime }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!--    指派司机-->
    <el-dialog title="选择司机" :visible.sync="showDriverListDialog"  width="50%">
      <el-table :data="driverList">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="driverId" />
        <el-table-column prop="realName" label="司机姓名" />
        <el-table-column prop="phone" label="司机电话" />
        <el-table-column label="驾驶证类型" align="center" prop="licenseType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.lg_driver_type" :value="scope.row.licenseType"/>
          </template>
        </el-table-column>

        <el-table-column label="司机状态" align="center" prop="status">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.lg_driver_status" :value="scope.row.status"/>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="assignDriver(scope.row)">指派</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>


    <!--    指派车辆-->
    <el-dialog title="选择车辆" :visible.sync="showCar"  width="50%">
      <el-table :data="carList">
      <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="vehicleId" />
        <el-table-column label="车辆类型" align="center" prop="vehicleType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.lg_vehicle_type" :value="scope.row.vehicleType"/>
          </template>
        </el-table-column>
      <el-table-column label="车辆长度" align="center" prop="vehicleLength" />
      <el-table-column label="车辆容积" align="center" prop="vehicleVolume" />
      <el-table-column label="车牌号" align="center" prop="licensePlate" />
      <el-table-column label="车辆状态" align="center" prop="vehicleStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.vehicleStatus"/>
        </template>
      </el-table-column>
        <el-table-column label="驾驶证类型" align="center" prop="licenseType">
          <template slot-scope="scope">
            <dict-tag :options="dict.type.lg_driver_type" :value="scope.row.licenseType"/>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="assignCar(scope.row)">指派</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>

<!--    仓库弹窗-->

    <el-dialog title="选择仓库" :visible.sync="warehouseDialogVisible" width="800px">
      <el-table :data="warehouseList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="cold_name" label="冷库名称"></el-table-column>
        <el-table-column prop="sub_name" label="子冷库名称"></el-table-column>
        <el-table-column prop="capacity" label="容量"></el-table-column>
      </el-table>

      <div slot="footer" class="dialog-footer">
        <el-button @click="warehouseDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSelection">确定</el-button>
      </div>
    </el-dialog>





    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1000px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="108px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单编号" prop="orderNumber"  >
              <el-input v-model="form.orderNumber" placeholder="请输入订单编号"  :disabled="isEdit" />
<!--             -->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卖家姓名" prop="sellerName" label-width="108px">
              <el-input v-model="form.sellerName" placeholder="请输入卖家姓名" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="卖家联系方式" prop="sellerContact" label-width="108px">
              <el-input v-model="form.sellerContact" placeholder="请输入卖家联系方式" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卖家提供重量" prop="providedWeight" label-width="108px">
              <el-input v-model="form.providedWeight" placeholder="请输入卖家提供重量" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="货物数量" prop="goodsQuantity" label-width="108px">
              <el-input v-model="form.goodsQuantity" placeholder="请输入货物数量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货物单位" prop="goodsUnit" label-width="108px">
              <el-select v-model="form.goodsUnit" placeholder="请选择货物单位">
                <el-option v-for="item in goodsUnitOptions" :key="item.id" :label="item.unitName" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="货物名称" prop="goodsName" label-width="108px">
              <el-select v-model="form.goodsName" placeholder="请选择货物名称" @change="handleGoodsChange">
                <!-- 使用 v-for 循环加载后端返回的选项 -->
                <el-option
                  v-for="item in goodsNameOptions"
                  :key="item.goodsId"
                  :label="item.goodsName"
                  :value="item.goodsId" />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="小类名称" prop="subGoodsName" label-width="108px">
              <el-select v-model="form.subGoodsName" placeholder="请选择小类名称">
                <el-option
                  v-for="item in subGoodsOptions"
                  :key="item.goodsId"
                  :label="item.goodsName"
                  :value="item.goodsId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预计存储天数" prop="storageDays" label-width="108px">
              <el-input v-model="form.storageDays" placeholder="请输入预计存储天数" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="起始地" prop="origin" label-width="108px">
              <el-input v-model="form.origin" placeholder="请输入起始地" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="目的地" prop="destination" label-width="108px">
              <el-input v-model="form.destination" placeholder="请输入目的地" />
            </el-form-item>
          </el-col>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="仓库地址" prop="warehouseAddress">-->
<!--              <el-input v-model="form.warehouseAddress" placeholder="请输入仓库地址" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="距离" prop="distance" label-width="108px">
              <el-input v-model="form.distance" placeholder="请输入距离" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="仓库类型" prop="cktype" label-width="108px">
              <el-select v-model="form.cktype" placeholder="请选择仓库类型">
                <el-option
                  v-for="item in warehouseTypes"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <!-- 控制整个仓库选择区域的显示与隐藏 -->
          <el-col :span="6" v-if="!isEdit">
            <el-form-item label="请选择仓库" prop="warehouseId" label-width="108px">
              <el-button type="primary" @click="openWarehouseDialog">选择仓库</el-button>
            </el-form-item>
          </el-col>

          <!-- 整个显示区域根据 isEdit 来控制是否显示 -->
          <el-col :span="16" v-if="!isEdit">
            <!-- 在非编辑模式下显示仓库信息 -->
            <div v-if="form.warehouseId">
              <p style="display: inline-block; margin-right: 10px;">
                冷库名称：<span style="border: 1px solid #dcdfe6; padding: 5px; border-radius: 4px; font-weight: bold; font-size: 16px;">{{ form.warehouseName }}</span>
              </p>
              <p style="display: inline-block; margin-right: 10px;">
                子冷库名称：<span style="border: 1px solid #dcdfe6; padding: 5px; border-radius: 4px; font-weight: bold; font-size: 16px;">{{ form.subWarehouseName }}</span>
              </p>
              <p style="display: inline-block;">
                容积：<span style="border: 1px solid #dcdfe6; padding: 5px; border-radius: 4px; font-weight: bold; font-size: 16px;">{{ form.capacity }} 立方米</span>
              </p>
            </div>
          </el-col>
        </el-row>


        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预估运费" prop="freightCost" label-width="108px">
              <el-input v-model="form.freightCost" placeholder="请输入预估货物费用" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预估仓储费用" prop="estimatedPrice" label-width="108px">
              <el-input v-model="form.estimatedPrice" placeholder="请输入预估价格" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="最终运费价格" prop="finalFreightPrice" label-width="108px">
              <el-input v-model="form.finalFreightPrice" placeholder="请输入最终运费" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最终存储价格" prop="finalGoodsPrice" label-width="108px">
              <el-input v-model="form.finalGoodsPrice" placeholder="请输入最终价格" />
            </el-form-item>
          </el-col>

        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="需要支付定金" prop="depositRequired" label-width="108px">
              <el-input v-model="form.depositRequired" placeholder="请输入需要支付定金" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="余款支付金额" prop="paymentAmount" label-width="108px" >
              <el-input v-model="form.paymentAmount" placeholder="请输入余额支付金额" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20" v-if="isEdit">
          <el-col :span="24">
            <el-form-item label="订单状态" prop="depositPaid" label-width="108px">
              <el-radio-group v-model="form.depositPaid">
                <el-radio v-for="dict in dict.type.lg_order_status" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>

import { listbill,getlistall,listexport, getBillById, updateBill, listOrders, getGoodsType,getSubGoodsByParentId,geUnitType,getColdType, addBill,delBill,listdriver,listcar,assignCarToOrder,assignDriverToOrder,getWarehouseType } from '@/api/order/everyorder'
import store from "@/store";
import axios from 'axios';

export default {
  name: "Bill",
  dicts: ['lg_order_status','sys_normal_disable','lg_vehicle_type','lg_driver_status','lg_driver_type'],
  data() {
    return {
      // 遮罩层
      userId:store.state.user.id, //将缓存的用户id赋值给userId
      userName:store.state.user.name, //将缓存的用户id赋值给userId
      loading: true,
      dateRange:[],
      assignedOrders: [], // 记录已指派司机的订单编号
      assignedOrder: [], // 记录已指派车辆的订单编号
      // 选中数组
      ids: [],
      // ... 其他数据 ...

      // 初始化价格区间数组，最小值为0，最大值为空
      priceRange: [null, null],
      // 非单个禁用
      single: true,
      selectedOrderNumber: null, // 记录当前订单编号
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showDriverListDialog: false, // 控制弹窗显示
      showDetailDialog : false,
      showCar: false,
      //选冷库区域
      warehouseDialogVisible: false, // 仓库选择对话框
      warehouseList: [], // 存储冷库数据
      selectedWarehouse: null, // 选中的仓库

      // 总条数
      total: 0,
      // 岗位表格数据
      everyList: [],
      driverList: [],
      carList : [],
      detail: {},
      //到时候要调接口
      goodsUnit: [],
      goodsUnitOptions: [],
      //货物名称
      goodsName: [
        // { id: 1, name: '蔬菜' },
        // { id: 2, name: '水果' }
      ],
      goodsNameOptions:[],
      //仓库类型
      cktype:[
        // { id: 1, name: '常温' },
        // { id: 2, name: '冷冻' }
      ],
      warehouseTypes:[],
      subGoodsName : [],
      subGoodsOptions: [], //存储货物小类的数据
      selectedGoodsId: null, //存储父级id
      driverLicenseType : [], //存储司机驾驶证类型
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      isEdit: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        depositPaid : null,
        createTime: null,
        orderNumber : null,
        sellerName : null,
        goodsName: null,
        cktype: null,
        priceRange: [null, null]
      },
      // 表单参数
      form: {
        warehouseId: "", // 选中的冷库 ID
        subWarehouseId: "", // 选中的子冷库 ID
        warehouseName: "", // 冷库名称
        subWarehouseName: "", // 子冷库名称
        cktype: null, // 绑定的值应为 id
        goodsNameUnits:null,
        subGoodsName: null // 选中的小类 ID（如果之前没有，务必添加）
      },
      rules: {
        orderNumber: [
          { required: true, message: "订单编号不能为空", trigger: "blur" }
        ],
        sellerName: [
          { required: true, message: "卖家姓名不能为空", trigger: "blur" }
        ],
        sellerContact: [
          { required: true, message: "卖家联系方式不能为空", trigger: "blur" }
        ],
        providedWeight: [
          { required: true, message: "卖家提供重量不能为空", trigger: "blur" }
        ],
        goodsQuantity: [
          { required: true, message: "货物数量不能为空", trigger: "blur" }
        ],
        goodsUnit: [
          { required: true, message: "货物单位不能为空", trigger: "change" }
        ],
        storageDays: [
          { required: true, message: "预计存储天数不能为空", trigger: "blur" }
        ],
        origin: [
          { required: true, message: "起始地不能为空", trigger: "blur" }
        ],
        destination: [
          { required: true, message: "目的地不能为空", trigger: "blur" }
        ],
        warehouseAddress: [
          { required: true, message: "仓库地址不能为空", trigger: "blur" }
        ],
        distance: [
          { required: true, message: "距离不能为空", trigger: "blur" }
        ],
        cktype: [
          { required: true, message: "仓库类型不能为空", trigger: "change" }
        ],
        freightCost: [
          { required: true, message: "预估货物费用不能为空", trigger: "blur" }
        ],
        estimatedPrice: [
          { required: true, message: "预估价格不能为空", trigger: "blur" }
        ],
        finalGoodsPrice: [
          { required: true, message: "最终价格不能为空", trigger: "blur" }
        ],
        finalFreightPrice: [
          { required: true, message: "最终运费不能为空", trigger: "blur" }
        ],
        depositRequired: [
          { required: true, message: "需要支付定金不能为空", trigger: "blur" }
        ],
        // paymentAmount: [
        //   { required: true, message: "余额支付金额不能为空", trigger: "blur" }
        // ],
        depositPaid: [
          { required: true, message: "是否支付定金不能为空", trigger: "change" }
        ],
        goodsName: [
          { required: true, message: "货物类型不能为空", trigger: "blur" }
        ],
        subGoodsName: [
          { required: true, message: "货物小类不能为空", trigger: "change" }
        ]
      }

    };
  },
  created() {

    this.getList();
    // this.getlistall();
    getWarehouseType().then(response => {
     // console.log(response.data)
    });
    const storedOrders = localStorage.getItem("assignedOrders");
    if (storedOrders) {
      this.assignedOrders = JSON.parse(storedOrders);
    }
    const storedOrder = localStorage.getItem("assignedOrder");
    if (storedOrder) {
      this.assignedOrder = JSON.parse(storedOrder);
    }


  },
  methods: {
    // //不带查询条件
    // getlistall() {
    //   getlistall(this.queryParams).then(response => {
    //     this.everyList = response.rows;
    //     this.total = response.total;
    //     this.loading = false;
    //   });
    // },
    /** 查询岗位列表 */
    getList() {
      this.loading = true;
      const queryParamsWithPriceRange = this.addDateRange(this.queryParams, this.dateRange, this.priceRange);
      // 确保 priceRange 被正确放入 queryParams 的 params 字段
      queryParamsWithPriceRange.params = {
        minPrice: this.priceRange[0] || '',
        maxPrice: this.priceRange[1] || ''
      };
      geUnitType().then(response => {
        this.goodsUnit = response.data.data;
      })
      getColdType().then(response => {
        this.cktype = response.data.data;
      })
      getGoodsType().then(response => {
        this.goodsName= response.data.data
      })
  //yzw
      // 获取订单列表（示例）
        listOrders(this.queryParams).then(response => {
          this.orderList = response.rows; // 假设返回的订单数据数组
          // 🚀 处理 `assignedOrders`，如果订单已有 `driver_id`，就加入数组
          this.assignedOrders = this.orderList
            .filter(order => order.driverId) // 只保留已有司机的订单
            .map(order => order.logisticsOrderNumber || order.orderNumber); // 取订单编号
          this.assignedOrder = this.orderList
            .filter(order => order.vehicleId) // 只保留已有司机的订单
            .map(order => order.logisticsOrderNumber || order.orderNumber); // 取订单编号
          // 存入 `localStorage`，防止刷新丢失状态
          localStorage.setItem("assignedOrders", JSON.stringify(this.assignedOrders));
        })



      listbill(queryParamsWithPriceRange).then(response => {
          this.everyList = response.rows;
          this.total =response.total;
          this.loading = false;
      });
      // getlistall(this.queryParams).then(response => {
      //   this.everyList = response.rows;
      //   this.total = response.total;
      //   this.loading = false;
      // });
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = Object.assign({}, {
        orderNumber: null,
        sellerName: null,
        goodsName: null,
        cktype: null,
        depositPaid: null,
        priceRange: [null, null]
      });
      // 重新赋值 priceRange，确保 Vue 触发视图更新
      this.resetForm("form");
    },
    handleGoodsChange(value) {
      // // 1. 清空小类选择框的值
      // this.form.subGoodsName = null;
      this.$forceUpdate();

      // 2. 清空小类选项
      this.subGoodsOptions = [];

      this.selectedGoodsId = value;  // 保存选中的大类ID
      if (value) {
        // 请求获取小类数据
        getSubGoodsByParentId(value).then(response => {
          this.subGoodsOptions = response.data.data || []; // 更新小类选项
          this.$nextTick(() => {
            // 确保 DOM 更新后，允许重新选择
            // 这里可以添加其他需要在 DOM 更新后执行的操作
          });
        }).catch(error => {
          console.error("获取小类失败", error);
          this.subGoodsOptions = []; // 请求失败时清空小类选项
        });
      } else {
        this.subGoodsOptions = []; // 如果没有选中货物名称，清空小类选项
      }
    },
    //选着仓库
    // 打开仓库选择弹窗
    openWarehouseDialog() {
      this.warehouseDialogVisible = true;
      this.fetchWarehouseData();
    },
    // 获取仓库数据
    fetchWarehouseData() {
      getWarehouseType().then(response => {
        if (response.code === 200) {
          this.warehouseList = response.data.data;
        }
      });
    },

    // 确认选择，把选中的仓库信息存到 form 里
    confirmSelection() {
      if (!this.selectedWarehouse) {
        this.$message.warning("请选择一个仓库！");
        return;
      }
      // 使用 this.$nextTick 确保数据更新后触发视图更新
      this.$nextTick(() => {
        this.form.warehouseId = this.selectedWarehouse.cold_id; // 冷库 ID
        this.form.subWarehouseId = this.selectedWarehouse.sub_id; // 子冷库 ID
        this.form.warehouseName = this.selectedWarehouse.cold_name; // 冷库名称
        this.form.subWarehouseName = this.selectedWarehouse.sub_name; // 子冷库名称
        this.form.capacity = this.selectedWarehouse.capacity; // 容积
        this.form.coldTypeId = this.selectedWarehouse.cold_type_id; // 冷库类型 ID
      });

      this.warehouseDialogVisible = false; // 关闭弹框
    },
    // 选择仓库，但不立即赋值
    selectWarehouse(row) {
      this.selectedWarehouse = row; // 暂存选中的仓库
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!=1
      this.multiple = !selection.length
      if (selection.length > 0) {
        this.selectedWarehouse = selection[0]; // 只取第一个选中的
      } else {
        this.selectedWarehouse = null;
      }
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
              this.form.createBy=this.userId,
              this.form.updateBy=this.userName,
              this.form.cktype = parseInt(this.form.cktype);
            //   //大类
            // this.form.goodsName = parseInt(this.form.goodsName);
              //传递小类id
            this.form.goodsName = parseInt(this.form.subGoodsName);

            updateBill(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBill(this.form).then(response => {

              this.form.createBy=this.userId,
                this.form.updateBy=this.userName,
                this.form.cktype = parseInt(this.form.cktype);
              this.form.goodsName = parseInt(this.form.subGoodsName);
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },



// 查看详情
    handlexq(row){
      this.showDetailDialog=true;
      const billId = row.id || this.ids
      getBillById(billId).then(response => {
        this.detail = response.data;
        // 这里转换 goodsUnit 为中文名称
        // this.goodsUnit= Number(this.detail.goodsUnit)
        const unit = this.goodsUnit.find(unit => unit.id === Number(this.detail.goodsUnit));
        this.detail.goodsUnit = unit ? unit.unitName : "未知单位";
      });

    },
    //指派司机
    handleDriver(row){
      this.selectedOrderNumber = row.orderNumber; // 记录订单号
      this.showDriverListDialog = true;
      listdriver(this.queryParams).then(response => {
        this.driverList = response.data.data;
      });
    },

    //选中司机
    assignDriver(driver){
      if (!this.selectedOrderNumber) {
        this.$message.error("订单编号缺失！");
        return;
      }
      // 获取选中的司机ID
      const driverId = driver.driverId;
      if (!driverId) {
        this.$message.error("请选择司机！");
        return;
      }
      // 调用接口传递订单编号和司机ID
      assignDriverToOrder(this.selectedOrderNumber, driverId).then(response => {
        if (response.code === 200) {
          this.$message.success("司机指派成功！");
          this.showDriverListDialog = false; // 关闭弹窗
          // **🚀 记录已指派的订单，修改按钮文本**
          if (!this.assignedOrders.includes(this.selectedOrderNumber)) {
            this.assignedOrders.push(this.selectedOrderNumber);
          }
          // 🚀 存入 `localStorage`
          localStorage.setItem("assignedOrders", JSON.stringify(this.assignedOrders));
          this.selectedOrderNumber = null; // 清空订单号
          this.getList();

        } else {
          this.$message.error("司机指派失败！");
        }
      });
      this.driverLicenseType=driver.licenseType;
    },

    handleCar(row){
      this.selectedOrderNumber = row.orderNumber; // 记录订单号
      this.showCar = true;
      listcar({ licenseType: this.driverLicenseType }).then(response => {
        this.carList = response.data.data;
      });

    },
    //选中车辆
    assignCar(car) {
      if (!this.selectedOrderNumber) {
        this.$message.error("订单编号缺失！");
        return;
      }
      // 获取选中的车辆ID
      const carId = car.vehicleId;
      if (!carId) {
        this.$message.error("请选择车辆！");
        return;
      }
      // 调用接口传递订单编号和车辆ID
      assignCarToOrder(this.selectedOrderNumber, carId).then(response => {
        if (response.code === 200) {
          this.$message.success("车辆指派成功！");
          this.showCar = false; // 关闭弹窗
          // **🚀 记录已指派的订单，修改按钮文本**
          if (!this.assignedOrder.includes(this.selectedOrderNumber)) {
            this.assignedOrder.push(this.selectedOrderNumber);
          }
          // 🚀 存入 `localStorage`
          localStorage.setItem("assignedOrder", JSON.stringify(this.assignedOrder));
          this.selectedOrderNumber = null; // 清空订单号
          this.getList();
        } else {
          this.$message.error("车辆指派失败！");
        }
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.isEdit = false;
      this.goodsNameOptions = this.goodsName;
      this.goodsUnitOptions = this.goodsUnit;
      this.warehouseTypes=this.cktype;
      this.reset();
      this.open = true;
      this.title = "添加订单";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      // console.log("row"+row.id)
      this.reset();
      this.isEdit = true;
      this.goodsUnitOptions = this.goodsUnit;
      this.warehouseTypes=this.cktype;
      this.goodsNameOptions = this.goodsName;
      const billId = row.id || this.ids
      getBillById(billId).then(response => {
        this.form = response.data;
        // 确保 goodsUnit 是数字类型
        this.form.goodsUnit = Number(response.data.goodsUnit);
        this.form.depositPaid= String(response.data.depositPaid);
        this.open = true;
        this.title = "修改订单";
      });
    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const billIds = row.id || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + billIds + '"的数据项？').then(function() {
        return delBill(billIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // /** 导出按钮操作 */
    // handleExport() {
    //   this.download('/lgorder/order/export', {
    //     ...this.queryParams
    //   }, `bill_${new Date().getTime()}.xlsx`)
    // }

    handleExport() {
      listexport().then((response) => {
        const content = response
        // 创建一个临时的链接元素
        const url = window.URL.createObjectURL(new Blob([content]));
        const link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', 'lgsllerorder.zip'); // 设置下载文件名
        document.body.appendChild(link);
        link.click();
        // 清理临时对象
        document.body.removeChild(link);
        window.URL.revokeObjectURL(url);
        })
        .catch((error) => {
          console.error('导出失败', error);
        });


    }



  }
};
</script>
